﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Nette.Utils
{
    class StorageManager
    {
        public static readonly string basePath = System.AppDomain.CurrentDomain.BaseDirectory;

        public static readonly string savePath = basePath + "/save/";

        public static string HistoryFile= "histroy";

        public static Encoding encoding = Encoding.UTF8;

        private static bool _IsHistoryChanged = false;

        private static List<string> _HistoryList = null;

        public static List<string>? GetHistory() 
        {
            if (_HistoryList == null) 
            {
                return null;
            }
            return Clone(_HistoryList);
        }
        public static void SetHistory(List<string>? strList)
        {
            _HistoryList = strList;
            _IsHistoryChanged = true;
        }
        public static void Load()
        {
            if(File.Exists(savePath + HistoryFile)) 
            {
                _HistoryList = FileTool.ReaderStringArray(savePath + HistoryFile, encoding);
            }
        }

        public static void SaveChange()
        {
            if (_IsHistoryChanged)
            {
                FileTool.WriteStringArray(_HistoryList, savePath+ HistoryFile, encoding);
                _IsHistoryChanged = false;
            }

        }

        public static void WriteHistory(object obj) {
            FileTool.WriteObject(obj,savePath + HistoryFile);
        }

        public static T? ReadHistory<T>()
        {
            return FileTool.ReadObject<T>(savePath + HistoryFile);
        }

        public static O Clone<O>(O o) 
        {
            O clo = JsonConvert.DeserializeObject<O>(JsonConvert.SerializeObject(o));
            return (O)clo;
        }

    }
}
